package com.zuihai.app.mvp.ui.widget.behavior;

import android.animation.ValueAnimator;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

import com.zuihai.app.R;
import com.zuihai.app.mvp.ui.widget.behavior.listener.IsChildScrollListener;
import com.zuihai.app.mvp.ui.widget.behavior.listener.NeedExpandListener;
import com.zuihai.app.mvp.ui.widget.behavior.listener.SupportNeedExpendListener;

/**
 * Created by Administrator on 2017/6/22 0022.
 */

public class TabBehavior extends CoordinatorLayout.Behavior implements NeedExpandListener {
    private final static int ANIMATOR_DURATION = 400;

    private int mTranslationMax;
    private int mChilHeight;
    private boolean mUp;
    private ValueAnimator mValueAnimator;
    private ViewPager mViewPager;
    private int mTranslationMin;
    private View mTabLayout;
    private boolean mControlChange;
    private boolean isExpande;

    public TabBehavior() {
    }

    public TabBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mValueAnimator = ValueAnimator.ofFloat(0, 1);
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
        mControlChange = true;
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
    }

    @Override
    public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
        super.onNestedScrollAccepted(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
        mChilHeight = child.getHeight();
        mTranslationMin = child.getContext().getResources().getDimensionPixelSize(R.dimen.dp_table_title);
        mTranslationMax = child.getHeight() - mTranslationMin;
        mViewPager = (ViewPager) coordinatorLayout.findViewById(R.id.view_pager);
        mTabLayout = child;
        if (mViewPager.getAdapter() != null && //有适配器
                mViewPager.getAdapter().getCount() > 0 &&//有item
                mViewPager.getAdapter() instanceof SupportNeedExpendListener &&
                ((SupportNeedExpendListener) mViewPager.getAdapter()).getNeedExpendListener() == null) {
            ((SupportNeedExpendListener) mViewPager.getAdapter()).setNeedExpendListener(this);
        }
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        mUp = dy > 0;
        if (mUp && mValueAnimator.isRunning()){
            consumed[1] = 0;
            return;
        }
        if (isChildScroll(child.getTranslationY())) {
            consumed[1] = 0;
            return;
        }

        consumed[1] = dy;//全部消耗
        int distance = (int) (-dy / 2);//降低移动的速度

        if (child.getTranslationY() + distance < -mTranslationMax) {
            distance = -mTranslationMax;
        } else if (child.getTranslationY() + distance > 0) {
            distance = 0;
        } else {
            distance = (int) (child.getTranslationY() + distance);
        }
        child.setTranslationY(distance);
    }

    public boolean isChildScroll(float translationY) {
        PagerAdapter adapter = mViewPager.getAdapter();
        boolean refresnEnable = translationY == 0;
        return mUp && translationY == -mTranslationMax ||
                !mUp && adapter != null && adapter.getCount() > 0 &&
                        adapter instanceof IsChildScrollListener && ((IsChildScrollListener) adapter).childScroll(mUp, refresnEnable);
    }

    @Override
    public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target) {
        super.onStopNestedScroll(coordinatorLayout, child, target);
        mControlChange = false;

        float translationY = child.getTranslationY();
        if (Math.abs(translationY) == mTranslationMax || translationY == 0) {
            return;
        }
        scroll();
    }

    private void scroll() {
        final float translationY = mTabLayout.getTranslationY();
        final float shouldMoveDistance;
        if (mUp) {
            //没超过 1/8
            if (Math.abs(translationY) < mTranslationMax / 8f) {
                shouldMoveDistance = Math.abs(translationY);
            } else {
                shouldMoveDistance = Math.abs(translationY) - mTranslationMax;
            }
        } else {//向下滑动
//            没超过 1/8
            if (Math.abs(translationY) > mTranslationMax * 7f / 8f) {
                shouldMoveDistance = -(mTranslationMax + translationY);
            } else {
                shouldMoveDistance = Math.abs(translationY);
            }
        }

        mValueAnimator.setDuration((long) (Math.abs(shouldMoveDistance) / mTranslationMax * ANIMATOR_DURATION));
        mValueAnimator.removeAllUpdateListeners();
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mTabLayout.setTranslationY(translationY + animation.getAnimatedFraction() * shouldMoveDistance);
            }
        });
        mValueAnimator.start();
    }

    /**
     * 关闭
     */
    public void needClose() {
        if (!mControlChange) {
            animator(false);
        }
    }

    /**
     * list fling到头的时候 展开
     */
    public void needExpand() {
        if (!mControlChange) {
            animator(true);
        }
    }

    private void animator(boolean expand) {
        if (!mValueAnimator.isRunning()) {
            isExpande = expand;
            final float shouldMoveDistance = expand ? mTranslationMax : -mTranslationMax;
            final float translationY = mTabLayout.getTranslationY();
            mValueAnimator.setDuration((long) (Math.abs(shouldMoveDistance) / mTranslationMax * ANIMATOR_DURATION));
            mValueAnimator.removeAllUpdateListeners();
            mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float percent = translationY + animation.getAnimatedFraction() * shouldMoveDistance;
                    if (percent <= 0 && percent >= -mTranslationMax) {
                        mTabLayout.setTranslationY(percent);
                    } else {
                        animation.removeUpdateListener(this);
                        animation.end();
                    }
                }
            });
            mValueAnimator.start();
        }
    }
}
